﻿//using MySql.Data.MySqlClient;
using MySqlConnector;
using System;
using System.Data;

public class MySqlDbHelper
{
    private readonly string _connectionString;

    public MySqlDbHelper(string connectionString)
    {
        _connectionString = connectionString;
    }

    private MySqlConnection GetConnection()
    {
        return new MySqlConnection(_connectionString);
    }

    public DataTable ExecuteQuery(string query, params MySqlParameter[] parameters)
    {
        using (var connection = GetConnection())
        {
            using (var command = new MySqlCommand(query, connection))
            {
                if (parameters != null)
                {
                    command.Parameters.AddRange(parameters);
                }

                using (var adapter = new MySqlDataAdapter(command))
                {
                    var dataTable = new DataTable();
                    adapter.Fill(dataTable);
                    return dataTable;
                }
            }
        }
    }

    public int ExecuteNonQuery(string query, params MySqlParameter[] parameters)
    {
        using (var connection = GetConnection())
        {
            connection.Open();
            using (var command = new MySqlCommand(query, connection))
            {
                if (parameters != null)
                {
                    command.Parameters.AddRange(parameters);
                }

                return command.ExecuteNonQuery();
            }
        }
    }

    public object ExecuteScalar(string query, params MySqlParameter[] parameters)
    {
        using (var connection = GetConnection())
        {
            connection.Open();
            using (var command = new MySqlCommand(query, connection))
            {
                if (parameters != null)
                {
                    command.Parameters.AddRange(parameters);
                }

                return command.ExecuteScalar();
            }
        }
    }

    public void ExecuteTransaction(Action<MySqlTransaction> transactionAction)
    {
        using (var connection = GetConnection())
        {
            connection.Open();
            using (var transaction = connection.BeginTransaction())
            {
                try
                {
                    transactionAction(transaction);
                    transaction.Commit();
                }
                catch
                {
                    transaction.Rollback();
                    throw;
                }
            }
        }
    }
}